package com.zmt.mrms.controller;

import java.text.ParseException;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zmt.mrms.entity.UserPatient;
import com.zmt.mrms.service.PatientService;

import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/patient")
public class PatientIsLoggedController {

	@Resource
	PatientService patientService;

	private HttpServletRequest request;
	private HttpServletResponse response;

	protected PatientIsLoggedController(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	@GetMapping("/medicalRecord")
	public String loggedMedicalRecord(Model model, @CookieValue("id") String id) {
		model.addAttribute("MedRecordslist", patientService.getPatientAllMedRecords(Integer.parseInt(id)));
		return "patient/loggedMedRecord";
	}

	@GetMapping("/prescription")
	public String loggedPrescription(Model model, @CookieValue("id") String id) {
		model.addAttribute("preRecordslist", patientService.getPatientAllPreRecord(Integer.parseInt(id)));
		return "patient/loggedPrescription";
	}

	@GetMapping("/personal")
	public String fpPersonal(Model model, @CookieValue(value = "id") String id) {
		UserPatient userPatient = patientService.findPatient(id);
		model.addAttribute("patient", userPatient);
		model.addAttribute("accountInfo", "onshow");
		model.addAttribute("personalInfo", "onshow");
		return "patient/fpPersonal";
	}

	@GetMapping("/personal/changeForAcc")
	public String changeForAccountInfo(Model model, @CookieValue(value = "id") String id,
			@RequestParam(value = "result", required = false) String result) {
		UserPatient userPatient = patientService.findPatient(id);
		model.addAttribute("patient", userPatient);
		model.addAttribute("accountInfo", "change");
		model.addAttribute("personalInfo", "onshow");
		if (result != null) {
//			System.out.println(result);
			if (result.equals("error")) {
				model.addAttribute("error", "服务器错误，请重试");
			} else {
				model.addAttribute("warning", result);
			}
		}
		return "patient/fpPersonal";
	}

	@PostMapping("/personal/changeForAcc")
	public String saveAccountInfo(UserPatient userPatient, @CookieValue(value = "id") String id,
			RedirectAttributes attributes) {
		userPatient.setId(Integer.parseInt(id));
		String result = patientService.updateAccountInfo(userPatient);
		if (result.equals("success")) {
			return "redirect:/patient/personal";
		} else {
			// RedirectAttributes 用于重定向携带参数
			attributes.addAttribute("result", result);
			return "redirect:/patient/personal/changeForAcc";
		}
	}

	@GetMapping("/personal/changeForPer")
	public String changeForPersonalInfo(Model model, @CookieValue(value = "id") String id,
			@RequestParam(value = "result", required = false) String result) {
		UserPatient userPatient = patientService.findPatient(id);
		model.addAttribute("patient", userPatient);
		model.addAttribute("accountInfo", "onshow");
		model.addAttribute("personalInfo", "change");
		if (result != null) {
			System.out.println(result);
			if (result.equals("error")) {
				model.addAttribute("error", "服务器错误，请重试");
			} else {
				model.addAttribute("warning", result);
			}
		}
		return "patient/fpPersonal";
	}

	@PostMapping("/personal/changeForPer")
	public String savePersonalInfo(UserPatient userPatient, @CookieValue(value = "id") String id,
			RedirectAttributes attributes) throws ParseException {
		userPatient.setId(Integer.parseInt(id));
//		System.out.println(userPatient);
		String result = patientService.updatePersonalInfo(userPatient);
		if (result.equals("success")) {
			return "redirect:/patient/personal";
		} else {
			// RedirectAttributes 用于重定向携带参数
			attributes.addAttribute("result", result);
			return "redirect:/patient/personal/changeForPer";
		}
	}

	@GetMapping("")
	public String homePage(Model model) {
		model.addAttribute("loginStatus", true);
		return "homepageFP";
	}

	@GetMapping("/register")
	public String registerPage() {
		return "registerPatient";
	}

	@PostMapping("/register")
	public String registerbyPatient(String email, String password, Model model) {
//		System.out.println(email + " " + password);
		String result = patientService.Register(email, password);
		if (result.equals("success")) {
			model.addAttribute("success", "注册成功，请登录");
			return "redirect:/patient/login";
		} else if (result.equals("error")) {
			model.addAttribute("error", "服务器错误，请刷新重试");
			return "registerPatient";
		} else {
			model.addAttribute("warning", result);
			return "registerPatient";
		}
	}

	@GetMapping("/logout")
	public String logout(Model model) {
		Cookie cookie1 = new Cookie("id", null);
		Cookie cookie2 = new Cookie("role", null);
		cookie1.setMaxAge(0);
		cookie2.setMaxAge(0);
		cookie1.setPath("/");
		cookie2.setPath("/");
		this.response.addCookie(cookie1);
		this.response.addCookie(cookie2);
		model.addAttribute("loginStatus", false);
		return "redirect:/";
	}

	@GetMapping("/login")
	public String loginPage() {
		return "loginPatient";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginbyPatient(String account, String password, Model model) {
//		System.out.println(account + " " + password);
		if ((account.length() == 0) || (password.length() == 0)) {
			model.addAttribute("warning", "账号或密码不能为空！");
			return "loginPatient";
		} else {
			UserPatient patient = patientService.Login(account, password);
//			System.out.println(patient);
			if (patient != null) {
				Cookie cookie1 = new Cookie("id", patient.getId().toString());
				Cookie cookie2 = new Cookie("role", patient.getRole());
				cookie1.setHttpOnly(true); // 前端仅可读，不可修改
				cookie1.setMaxAge(24 * 60 * 60); // 24小时过期
				cookie2.setHttpOnly(true);
				cookie2.setMaxAge(24 * 60 * 60);
				cookie1.setPath("/");
				cookie2.setPath("/");
				this.response.addCookie(cookie1);
				this.response.addCookie(cookie2);
				model.addAttribute("loginStatus", true);
				return "redirect:/patient";
			} else {
				model.addAttribute("error", "账号或密码错误");
				return "loginPatient";
			}
		}

	}

}
